import { createRouter, createWebHashHistory } from 'vue-router';
import { useAppUserStore, useAppMenuStore } from '@/stores';
import { ElMessage } from 'element-plus';

const basicRoutes = [
  {
    path: '/login',
    component: () => import('@/views/framework/LoginPage.vue')
  }
];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [...basicRoutes]
});

function mAddRoute() {
  let appMenuStore = useAppMenuStore();
  var routes = {
    name: 'framework_layout',
    path: '/',
    component: () => import('@/views/layout/FrameworkLayout.vue'),
    redirect: '/commodity/manage',
    children: appMenuStore.getLocalAppMenusRouteTable()
  };

  router.addRoute(routes);
}

router.beforeEach(async (to, from, next) => {
  let appUserStore = useAppUserStore();
  if (to.path == '/login') {
    next();
    return;
  }

  if (!appUserStore.isHasUserToken()) {
    next({ path: '/login', replace: true });
    return;
  }

  if (!appUserStore.isUserTokenValid()) {
    let resfreshResult = await appUserStore.refreshToken();
    if (!resfreshResult) {
      ElMessage.error('请先登录...');
      next({ path: '/login', replace: true });
      return;
    }
  }

  // 判断路由数量与基本路由数量是否相同
  if (router.getRoutes().length == basicRoutes.length) {
    // 如果相同，则表示是 刷新页面 或 第一次进入，添加路由
    mAddRoute();
    next({ path: to.path, params: to.params, query: to.query, replace: true });
  } else {
    // 如果不相同，则表示是 已经添加了路由
    next();
  }
});

export default router;
